﻿using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace ExcelFileQueryTool
{
    public partial class frmClientDetail : Form
    {
        private int? _clientId;

        public frmClientDetail(int? clientId)
        {
            InitializeComponent();

            cboxType.Items.AddRange(AppConfig.ClientTypes);

            cboxType.SelectedIndex = 0;
            cboxGender.SelectedIndex = 0;

            if (clientId.HasValue)
                LoadData(clientId.Value);
        }

        private void btnCancle_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            var clientOK = false;
            var fileOK = false;
            var salesOK = false;

            var newData = CollectFormData();

            CrmPeopleService svc = new CrmPeopleService(AppConfig.DBConnectionString);

            if (_clientId.HasValue)
            {
                // keep oldData before update
                CRMPeople oldData = null;
                if (chkUpdateFile.Checked)
                    oldData = svc.GetById(_clientId.Value);

                svc.Update(newData);
                clientOK = true;

                if (chkUpdateSales.Checked)
                {
                    BillSalesService billSvc = new BillSalesService(AppConfig.DBConnectionString);
                    billSvc.UpdateClientNameById(_clientId.Value, newData.Name);
                    salesOK = true;
                }


                if (chkUpdateFile.Checked
                    && (oldData.TypeCode != newData.TypeCode || oldData.Name != newData.Name))
                {
                    var oldFile = Path.Combine(AppConfig.SourceFolder, oldData.TypeCode, string.Format("[对数表]{0}.xlsx", oldData.Name));

                    while (File.Exists(oldFile) == false)
                    {
                        using (OpenFileDialog fileDiag = new OpenFileDialog())
                        {
                            fileDiag.Title = "必须选择一个客户文件";
                            fileDiag.InitialDirectory = AppConfig.SourceFolder;
                            fileDiag.Multiselect = false;
                            fileDiag.Filter = AppConfig.ClientFileChooseFilter;

                            if (fileDiag.ShowDialog() == DialogResult.OK)
                                oldFile = fileDiag.FileName;
                        }
                    };

                    var newFile = Path.Combine(AppConfig.SourceFolder, newData.TypeCode, string.Format("[对数表]{0}.xlsx", newData.Name));

                    try
                    {
                        // 只做名称和类型处理，对数表内的联系信息需要手动更新
                        File.Move(oldFile, newFile);
                        fileOK = true;
                    }
                    catch (Exception ex)
                    {
                        //MessageBox.Show("移动文件失败，请进行手动操作！" + ex.Message, "提示");
                        MessageDispatcherManager.DispatchMessage(
                            new AppMessage
                            {
                                Time = DateTime.Now,
                                Level = AppMessageLevel.Info,
                                Title = "移动文件失败，请进行手动操作！",
                                Content = ex.Message
                            });
                    }
                }
            }
            else
            {
                svc.Add(newData);
                clientOK = true;
            }

            MessageDispatcherManager.DispatchMessage(
                            new AppMessage
                            {
                                Time = DateTime.Now,
                                Level = AppMessageLevel.Info,
                                Title = "客户详情操作",
                                Content = string.Format("客户信息操作：{0}\r\n销售记录操作：{1}\r\n客户文件操作：{2}"
                                                        , clientOK ? "OK" : "NO"
                                                        , salesOK ? "OK" : "NO"
                                                        , fileOK ? "OK" : "NO")
                            });

            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }

        private void LoadData(int id)
        {
            CrmPeopleService svc = new CrmPeopleService(AppConfig.DBConnectionString);
            var data = svc.GetById(id);

            if (data == null)
            {
                //MessageBox.Show("指定的数据不存在，进入新增模式。Id=" + id);
                MessageDispatcherManager.DispatchMessage(
                            new AppMessage
                            {
                                Time = DateTime.Now,
                                Level = AppMessageLevel.Info,
                                Title = "客户详情操作",
                                Content = "指定的数据(Id=" + id + ")不存在，进入新增模式。"
                            });
            }
            else
            {
                _clientId = id;
                cboxGender.SelectedItem = data.Gender;
                cboxType.SelectedItem = data.TypeCode;
                txtAddress.Text = data.Address;
                txtName.Text = data.Name;
                txtNickName.Text = data.NickName;
                txtNote.Text = data.Note;
                txtPhone.Text = data.Telephone;

                chkUpdateSales.Visible = true;
                chkUpdateSales.Checked = false;

                chkUpdateFile.Visible = true;
                chkUpdateFile.Checked = false;
            }
        }

        private CRMPeople CollectFormData()
        {
            CRMPeople data = new CRMPeople();
            data.CreatedTime = DateTime.Now;
            data.LastUpdatedTime = DateTime.Now;
            data.Id = _clientId;
            data.Address = txtAddress.Text.Trim();
            data.Gender = cboxGender.SelectedItem.ToString();
            data.Name = txtName.Text.Trim();
            data.IndexCode = StringHelper.ChinessWordToPinYin(data.Name);
            data.NickName = txtNickName.Text.Trim();
            data.Note = txtNote.Text.Trim();
            data.Status = (short)DBRecordStatus.Normal;
            data.Telephone = txtPhone.Text.Trim();
            data.TypeCode = cboxType.SelectedItem.ToString();

            return data;
        }

        private void txtName_TextChanged(object sender, EventArgs e)
        {
            if (chkUpdateSales.Visible)
                chkUpdateSales.Checked = true;

            if (chkUpdateFile.Visible)
                chkUpdateFile.Checked = true;
        }

        private void cboxType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (chkUpdateFile.Visible)
                chkUpdateFile.Checked = true;
        }
    }
}